<template>
    <view :style="{ '--color': color }">
        <view class="SignatureBox">
            <view class="signature-header">
                <text class="black size28">请在此手写签名</text>
                <view class="signature-actions">
                    <text class="clear-btn" @click="clearCanvas">清除</text>
                    <!-- <text class="init-btn" @click="manualInit" v-if="!isCanvasReady">重新初始化</text>
                    <text class="debug-btn" @click="debugCanvas" style="color: #ff6600; border: 1px solid #ff6600; padding: 8rpx 16rpx; border-radius: 8rpx; font-size: 20rpx; margin: 0 10rpx">
                        调试
                    </text> -->
                    <text class="save-btn" @click="saveSignature">保存</text>
                </view>
            </view>
            <view class="sigbBox">
                <canvas
                    class="signature-canvas"
                    canvas-id="signatureCanvas"
                    id="signatureCanvas"
                    @touchstart="handleTouchStart"
                    @touchmove="handleTouchMove"
                    @touchend="handleTouchEnd"
                    disable-scroll
                    type="2d"
                ></canvas>
            </view>
        </view>
    </view>
</template>

<script>
    import { mapState } from 'vuex';
    export default {
        props: ['Type'],
        data() {
            return {
                context: null,
                isCanvasReady: false,
                canvasId: null,
                canvas: null,
                isDrawing: false,
                lastX: 0,
                lastY: 0,
                hasDrawn: false // 记录是否已经进行过签名
            };
        },
        onReady() {
            // 增加延迟确保DOM完全渲染
            setTimeout(() => {
                this.initCanvas();
            }, 300);
        },

        mounted() {
            // H5环境下的初始化
            // #ifdef H5
            this.$nextTick(() => {
                setTimeout(() => {
                    this.initCanvas();
                }, 100);
            });
            // #endif
        },

        methods: {
            // 初始化Canvas
            initCanvas(retryCount = 0) {
                // #ifdef H5
                try {
                    this.context = uni.createCanvasContext('signatureCanvas');
                    if (this.context) {
                        this.context.lineCap = 'round';
                        this.context.lineWidth = 3;
                        this.context.strokeStyle = '#000000';
                        this.isCanvasReady = true;
                        console.log('H5 Canvas 初始化完成');
                    } else {
                        throw new Error('无法创建Canvas上下文');
                    }
                } catch (error) {
                    if (retryCount < 3) {
                        setTimeout(() => {
                            this.initCanvas(retryCount + 1);
                        }, 500);
                    }
                }
                // #endif

                // #ifdef MP-WEIXIN
                const query = uni.createSelectorQuery().in(this);
                query
                    .select('#signatureCanvas')
                    .fields({ node: true, size: true })
                    .exec((res) => {
                        console.log('Canvas查询结果：', res);
                        if (res && res[0] && res[0].node) {
                            try {
                                const canvas = res[0].node;
                                this.canvas = canvas;
                                this.context = canvas.getContext('2d');

                                if (this.context) {
                                    // 设置画布大小
                                    const dpr = uni.getWindowInfo().pixelRatio || 2;
                                    canvas.width = res[0].width * dpr;
                                    canvas.height = res[0].height * dpr;

                                    // 设置画笔样式
                                    this.context.scale(dpr, dpr);
                                    this.context.lineCap = 'round';
                                    this.context.lineJoin = 'round';
                                    this.context.lineWidth = 3;
                                    this.context.strokeStyle = '#000000';
                                    this.isCanvasReady = true;
                                    console.log('微信小程序 Canvas 初始化完成', {
                                        width: canvas.width,
                                        height: canvas.height,
                                        dpr
                                    });
                                } else {
                                    throw new Error('无法获取Canvas 2D上下文');
                                }
                            } catch (error) {
                                console.error('Canvas 2D 初始化错误：', error);
                                this.retryInit(retryCount);
                            }
                        } else {
                            console.error('Canvas 初始化失败：未找到 #signatureCanvas 节点');
                            this.retryInit(retryCount);
                        }
                    });
                // #endif
            },

            // 重试初始化
            retryInit(retryCount) {
                if (retryCount < 5) {
                    const delay = (retryCount + 1) * 500; // 递增延迟
                    console.log(`Canvas初始化失败，${delay}ms后进行第${retryCount + 1}次重试`);
                    setTimeout(() => {
                        this.initCanvas(retryCount + 1);
                    }, delay);
                } else {
                    console.error('Canvas初始化重试次数已达上限，初始化失败');
                    uni.showToast({
                        title: 'Canvas初始化失败，请重新打开页面',
                        icon: 'none',
                        duration: 3000
                    });
                }
            },
            // 开始绘制
            handleTouchStart(e) {
                if (!this.isCanvasReady || !this.context) return console.log('Canvas未准备就绪，无法开始绘制');
                this.isDrawing = true;
                this.hasDrawn = true; // 标记已经开始绘制
                const touch = e.touches[0];
                this.lastX = touch.x;
                this.lastY = touch.y;

                // #ifdef H5
                this.context.beginPath();
                this.context.moveTo(this.lastX, this.lastY);
                // #endif

                // #ifdef MP-WEIXIN
                this.context.beginPath();
                this.context.moveTo(this.lastX, this.lastY);
                // #endif
            },
            // 绘制中
            handleTouchMove(e) {
                if (!this.isDrawing || !this.isCanvasReady || !this.context) return;
                const touch = e.touches[0];

                // #ifdef H5
                this.context.lineTo(touch.x, touch.y);
                this.context.stroke();
                this.context.draw(true);
                this.lastX = touch.x;
                this.lastY = touch.y;
                // #endif

                // #ifdef MP-WEIXIN
                // 根据经验，Canvas 2D模式不需要频繁调用draw()
                this.context.lineTo(touch.x, touch.y);
                this.context.stroke();
                this.lastX = touch.x;
                this.lastY = touch.y;
                // #endif
            },
            // 结束绘制
            handleTouchEnd() {
                if (this.isDrawing) {
                    this.isDrawing = false;
                    // #ifdef MP-WEIXIN
                    // 在绘制结束时关闭路径，保证签名连续性
                    if (this.context) {
                        this.context.closePath();
                    }
                    // #endif
                }
            },
            // 清除画布
            clearCanvas() {
                this.hasDrawn = false; // 重置绘制状态

                // #ifdef H5
                this.context.clearRect(0, 0, 1000, 1000); // 使用更大的尺寸确清除
                this.context.draw(true);
                // #endif

                // #ifdef MP-WEIXIN
                const canvas = this.context.canvas;
                this.context.clearRect(0, 0, canvas.width, canvas.height);
                // #endif
            },
            // 检查canvas是否有内容
            isCanvasEmpty() {
                // #ifdef H5
                try {
                    const canvas = document.getElementById('signatureCanvas');
                    if (!canvas) return true;

                    const ctx = canvas.getContext('2d');
                    const imageData = ctx.getImageData(0, 0, canvas.width, canvas.height);
                    const data = imageData.data;

                    // 检查是否所有像素都是透明的
                    for (let i = 3; i < data.length; i += 4) {
                        if (data[i] !== 0) {
                            return false; // 找到非透明像素，说明有内容
                        }
                    }
                    return true; // 所有像素都是透明的，画布为空
                } catch (error) {
                    console.error('H5检查画布内容失败:', error);
                    return false; // 出错时假设有内容，允许保存
                }
                // #endif

                // #ifdef MP-WEIXIN
                try {
                    if (!this.canvas || !this.context) return true;

                    const imageData = this.context.getImageData(0, 0, this.canvas.width, this.canvas.height);
                    const data = imageData.data;

                    // 检查是否所有像素都是透明的
                    for (let i = 3; i < data.length; i += 4) {
                        if (data[i] !== 0) {
                            return false; // 找到非透明像素，说明有内容
                        }
                    }
                    return true; // 所有像素都是透明的，画布为空
                } catch (error) {
                    console.error('微信小程序检查画布内容失败:', error);
                    return false; // 出错时假设有内容，允许保存
                }
                // #endif
            },

            // 保存签名
            saveSignature() {
                if (!this.isCanvasReady || !this.context) {
                    uni.showToast({
                        title: 'Canvas未初始化，请稍后再试',
                        icon: 'none'
                    });
                    return;
                }

                // 检查是否已经进行签名
                if (!this.hasDrawn) {
                    uni.showToast({
                        title: '请先进行签名',
                        icon: 'none',
                        duration: 2000
                    });
                    return;
                }

                console.log('开始保存签名');
                uni.showLoading({
                    title: '保存中...'
                });

                // #ifdef H5
                this.context.draw(true, () => {
                    uni.canvasToTempFilePath({
                        canvasId: 'signatureCanvas',
                        success: (res) => {
                            console.log('H5保存成功:', res);
                            uni.hideLoading();
                            this.uploadSign(res.tempFilePath);
                        },
                        fail: (err) => {
                            console.error('H5保存失败:', err);
                            uni.hideLoading();
                            uni.showToast({
                                title: '保存失败',
                                icon: 'error'
                            });
                        }
                    });
                });
                // #endif

                // #ifdef MP-WEIXIN
                try {
                    // 优先使用已保存的Canvas实例
                    if (this.canvas) {
                        uni.canvasToTempFilePath(
                            {
                                canvas: this.canvas,
                                success: async (res) => {
                                    try {
                                        // 将临时文件转换为base64
                                        const base64Data = await this.convertToBase64(res.tempFilePath);
                                        uni.hideLoading();
                                        this.uploadSign(base64Data);
                                    } catch (error) {
                                        uni.hideLoading();
                                        this.$Toast('图片处理失败');
                                    }
                                },
                                fail: (err) => {
                                    uni.hideLoading();
                                    this.$Toast(`保存失败: ' + (err.errMsg || '未知错误`);
                                }
                            },
                            this
                        );
                    } else {
                        // 备用方案：重新查询Canvas节点

                        const query = uni.createSelectorQuery().in(this);
                        query
                            .select('#signatureCanvas')
                            .fields({ node: true, size: true })
                            .exec((res) => {
                                if (res && res[0] && res[0].node) {
                                    const canvas = res[0].node;
                                    uni.canvasToTempFilePath(
                                        {
                                            canvas: canvas,
                                            success: async (res) => {
                                                try {
                                                    // 将临时文件转换为base64
                                                    const base64Data = await this.convertToBase64(res.tempFilePath);
                                                    uni.hideLoading();
                                                    this.uploadSign(base64Data);
                                                } catch (error) {
                                                    uni.hideLoading();
                                                    this.$Toast('图片处理失败');
                                                }
                                            },
                                            fail: (err) => {
                                                uni.hideLoading();
                                                this.$Toast(`保存失败: ' + (err.errMsg || '未知错误`);
                                            }
                                        },
                                        this
                                    );
                                } else {
                                    uni.hideLoading();
                                    this.$Toast(`Canvas节点获取失败，请重新初始化`);
                                }
                            });
                    }
                } catch (error) {
                    uni.hideLoading();
                    this.$Toast(`保存异常${error.message}`);
                }
                // #endif
            },

            // 手动重新初始化
            manualInit() {
                this.isCanvasReady = false;
                this.context = null;
                this.canvas = null;
                this.$showLoading('');
                setTimeout(() => {
                    this.initCanvas(0);
                    setTimeout(() => {
                        this.$hideLoading();
                    }, 1000);
                }, 100);
            },

            uploadSign(file_base64) {
                this.$showLoading('上传中...');

                this.$http
                    .post({
                        url: '/lfgApi/uploadSign',
                        data: {
                            file_base64
                        }
                    })
                    .then((res) => {
                        this.$hideLoading();

                        if (res.code != 200) {
                            this.$Toast(res.msg);
                            return;
                        }
                        const result = res.data;
                        this.$Toast('签名保存成功');

                        // 保存成功后重置状态
                        this.hasDrawn = false;
                        this.clearCanvas();

                        this.$emit('Update', result);
                    })
                    .catch((error) => {
                        this.$hideLoading();
                        this.$Toast(`上传失败${error.message || '网络错误'}`);
                    });
            },

            // 调试功能
            debugCanvas() {
                console.log('=== Canvas 调试信息 ===');
                console.log('isCanvasReady:', this.isCanvasReady);
                console.log('context:', this.context);
                console.log('canvas:', this.canvas);
                console.log('isDrawing:', this.isDrawing);

                const debugInfo = {
                    isCanvasReady: this.isCanvasReady,
                    hasContext: !!this.context,
                    hasCanvas: !!this.canvas,
                    canvasWidth: this.canvas ? this.canvas.width : 'N/A',
                    canvasHeight: this.canvas ? this.canvas.height : 'N/A'
                };

                uni.showModal({
                    title: 'Canvas调试信息',
                    content: JSON.stringify(debugInfo, null, 2),
                    showCancel: false
                });
            },

            // 将临时文件转换为base64
            convertToBase64(tempFilePath) {
                return new Promise((resolve, reject) => {
                    // #ifdef MP-WEIXIN
                    const fs = uni.getFileSystemManager();
                    fs.readFile({
                        filePath: tempFilePath,
                        encoding: 'base64',
                        success: (res) => {
                            // 添加data:image/png;base64,前缀
                            const base64Data = 'data:image/png;base64,' + res.data;
                            resolve(base64Data);
                        },
                        fail: (error) => {
                            reject(error);
                        }
                    });
                    // #endif

                    // #ifdef H5
                    // H5环境下直接返回路径
                    resolve(tempFilePath);
                    // #endif
                });
            },

            // 可选：不带MIME类型的base64转换
            convertToBase64Only(tempFilePath) {
                return new Promise((resolve, reject) => {
                    // #ifdef MP-WEIXIN
                    const fs = uni.getFileSystemManager();
                    fs.readFile({
                        filePath: tempFilePath,
                        encoding: 'base64',
                        success: (res) => {
                            console.log('纯base64转换成功');
                            // 只返回base64字符串，不带MIME类型
                            resolve(res.data);
                        },
                        fail: (error) => {
                            console.error('纯base64转换失败:', error);
                            reject(error);
                        }
                    });
                    // #endif

                    // #ifdef H5
                    resolve(tempFilePath);
                    // #endif
                });
            }
        },
        computed: {
            ...mapState(['color', 'bid', 'vid'])
        }
    };
</script>

<style lang="scss" scoped>
    .signature-canvas {
        width: 100%;
        height: 100%;
        box-sizing: border-box;
        display: block;
    }
    .SignatureBox {
        width: 100%;
        padding: 20rpx;
        display: flex;
        flex-direction: column;
        margin-top: 20rpx;

        .signature-header {
            display: flex;
            justify-content: space-between;
            align-items: center;
            margin-bottom: 20rpx;

            .signature-actions {
                display: flex;
                gap: 20rpx;

                .clear-btn,
                .save-btn,
                .init-btn {
                    padding: 10rpx 20rpx;
                    border-radius: 10rpx;
                    font-size: 24rpx;
                    cursor: pointer;
                }

                .clear-btn {
                    color: #999;
                    border: 1px solid #999;
                    background: #fff;
                }

                .init-btn {
                    color: #ff9500;
                    border: 1px solid #ff9500;
                    background: #fff;
                }

                .save-btn {
                    color: #fff;
                    background: var(--color, #007aff);
                    border: 1px solid var(--color, #007aff);
                }
            }
        }

        .sigbBox {
            width: 100%;
            height: 380rpx;
            border: 1px solid #666;
            border-radius: 10rpx;
            position: relative;
            overflow: hidden;
            background: #ffffff;

            .signature-canvas {
                width: 100%;
                height: 100%;
                background: transparent;
            }
        }
    }
</style>